// mircoApp/ai-create/DigitalHuman/index.js
let app = getApp();
const skinBehavior = require('../../../utils/themeSkin/skinBehavior');
Page({
  behaviors: [skinBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    imgPath: app.globalData.imgPath,
    tempFilePath: null,
    errDomo: [{
      text: '多张面孔',
      icon: 10
    },{
      text: '面部过大',
      icon: 11
    },{
      text: '面部被遮挡',
      icon: 12
    },{
      text: '未检测到面孔',
      icon: 13
    }],
    uploadIng: false,//是否正在上传
    videoProgress: 0,

    name: '',
    showAgreement: false,

    fileList: [],
    upload_file_max_size: "",
    upload_file_tip: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  async getData(){
    let urlStr = app.getNetAddresss('plugin.ai-create.frontend.controllers.create.body-clone');
    let response = await app._postNetWork({
      url: urlStr,
      data: {
        business_id: this.options.business_id || 0
      }
    });
    let { result, msg, data } = response.data;
    if(!result) return app.tips(msg);
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.data.themeBaseColor
    });
    this.setData({
      body_clone_agreement: data.body_clone_agreement,
      showAgreement: true,
      upload_file_max_size: data.upload_file_max_size,
      upload_file_tip: data.upload_file_tip
    });
  },
  toNextPage(){
    wx.navigateBack({
      delta: 1,
      fail: ()=>{
        wx.redirectTo({
          url: '/mircoApp/ai-create/SpacePortal/index'
        })
      }
    })
  },
  onClickVal(e) {
    let {
      name,
      val
    } = e.currentTarget.dataset;
    this.setData({
      [name]: val
    });
  },

  chooseMedia(){
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'front',
      success:(res)=> {
        console.log(res)
        let size = parseFloat(res.tempFiles[0].size/1024/1024).toFixed(1)
        if(size > this.data.upload_file_max_size) {
          app.tips(this.data.upload_file_tip);
          return
        }
        this.setData({
          tempFilePath: res.tempFiles[0].tempFilePath,
          thumbTempFilePath: res.tempFiles[0].thumbTempFilePath || null,
        })
        if(this.data.thumbTempFilePath){
          this.uploadImageM();//有封面，先上传封面
        }
      }
    })
  },
  submit(){
    if(!this.data.tempFilePath) {
      app.tips('请上传分身视频','error');
      return;
    }
    if(!this.data.name) {
      app.tips('请设置分身名称','error');
      return;
    }
    this.setData({
      uploadIng: true
    });
    this.uploadFile();//提交上传
  },
  uploadImageM() {
    //上传封面
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.uploadFile({
      url: urlStr,
      filePath: this.data.thumbTempFilePath,
      name: 'file',
      formData: {},
      success: (res)=> {
        let resData = JSON.parse(res.data);
        if (resData.result == 1) {
          this.cover_img = resData.data.img_url;
          this.data.refer_img = resData.data.img_url;
          this.setData({
            fileList: [{
              url: resData.data.img_url
            }]
          })
          // this.uploadFile();//提交上传
        } else {
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 1500
          });
        }
      }
    });
  },
  uploadFile(){
    let wx_token = wx.getStorageSync('wx_token');
    let session = wx.getStorageSync('session');
    let urlStr = app.getNetAddresss("plugin.ai-create.frontend.controllers.create.body-clone.create");
    urlStr += '&3rd_session=' + session;
    const uploadTask = wx.uploadFile({
      url: urlStr, //仅为示例，非真实的接口地址
      filePath: this.data.tempFilePath,
      name: 'file',
      formData:{
        'name': this.data.name,
        business_id: this.options.business_id,
        cover_img: this.cover_img || '',
        refer_img: this.data.refer_img
      },
      header: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Cookie: "PHPSESSID=" + wx_token,
      },
      success:(res)=>{
        let resData = JSON.parse(res.data);
        this.setData({
          uploadIng: false
        });
        if (resData.result == 1) {
          wx.redirectTo({
            url: '/mircoApp/ai-create/SpaceDetails/index?tab=1&business_id=' + this.options.business_id || 0
          })
        } else {
          app.tips(resData.msg)
        }
      },complete: (e) => {
        console.log('complete',e)
      },
      fail:(err)=>{
        console.log('fail',err)
        this.setData({
          uploadIng: false
        });
        app.tips(`上传失败 ${err ? ` - ${err.errMsg}` : ""}`)
      }
    });

    uploadTask.onProgressUpdate((res) => {
      this.setData({
        videoProgress: res.progress //上传进度
      });
    })
  },

  // 前置校验方法
  async beforeRead (event) {
    const { file, callback } = event.detail;
    // 文件大小校验
    if (file.size > 10 * 1024 * 1024) {
      wx.showToast({ title: '文件不能超过10MB', icon: 'none' })
      return false
    }

    // 文件类型校验
    const validExt = ['jpeg', 'jpg', 'png', 'bmp', 'webp']
    const ext = file.url.split('.').pop().toLowerCase()
    if (!validExt.includes(ext)) {
      wx.showToast({ title: '仅支持图片格式：JPEG/JPG/PNG/BMP/WEBP', icon: 'none' })
      return false
    }

    // 图片尺寸校验
    try {
      const imageInfo = await this.getImageInfo(file.tempFilePath)
      const maxSide = Math.max(imageInfo.width, imageInfo.height)
      const ratio = Math.max(
        imageInfo.width / imageInfo.height,
        imageInfo.height / imageInfo.width
      )

      if (maxSide > 4096) {
        wx.showToast({ title: '图片最大边长不能超过4096px', icon: 'none' })
        return false
      }

      if (ratio > 2) {
        wx.showToast({ title: '图片长宽比不能超过2:1', icon: 'none' })
        return false
      }
      callback(true);
      return true
    } catch (error) {
      wx.showToast({ title: '图片信息获取失败', icon: 'none' })
      return false
    }
  },

  // 获取图片信息（Promise封装）
  getImageInfo(path) {
    return new Promise((resolve, reject) => {
      wx.getImageInfo({
        src: path,
        success: resolve,
        fail: reject
      })
    })
  },

  // 上传文件
  uploadImage(event) {
    const { file } = event.detail
    this.setData({
      fileList: [{
        url: file.url,
        size: file.size
      }]
    })

    // 这里添加实际的上传服务器逻辑
    let urlStr = app.getNetAddresss('upload.uploadPic');
    wx.uploadFile({
      url: urlStr,
      filePath: file.url,
      name: 'file',
      success: (res)=> {
        let resData = JSON.parse(res.data);
        if (resData.result == 1) {
          this.setData({
            refer_img: resData.data.img_url
          })
        } else {
          wx.showToast({
            title: resData.msg,
            icon: 'none',
            duration: 1500
          });
        }
      }
    })
  },

  // 删除文件
  onDelete() {
    this.setData({ fileList: [] })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      path: '/mircoApp/ai-create/SpacePortal/index',
    };
  }
})